<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const form = ref({
  id: '',
  dataValue: ''
})

const formdata = ref({
  dataValue: ''
})

let res = localStorage.getItem('loginUser')
const myId = JSON.parse(res).id

// WebSocket相关变量
let websocket = null
let clientId = Math.random().toString(36).substr(2)

// 初始化WebSocket连接
const initWebSocket = () => {
  // 判断当前浏览器是否支持WebSocket
  if ('WebSocket' in window) {
    // 连接WebSocket节点，这里的地址需要根据你的后端服务地址进行调整
    websocket = new WebSocket(`ws://localhost:8080/ws/${myId}`)
    
    // 连接发生错误的回调方法
    websocket.onerror = () => {
      appendMessage("WebSocket连接发生错误")
    }
    
    // 连接成功建立的回调方法
    websocket.onopen = () => {
      appendMessage("WebSocket连接成功")
    }
    
    // 接收到消息的回调方法
    websocket.onmessage = (event) => {
      try {
        // 尝试解析JSON格式的消息
        const data = JSON.parse(event.data);
        if (data.fromUserId && data.message) {
          appendMessage(`用户${data.fromUserId}说: ${data.message}`)
        } else {
          appendMessage("收到消息: " + event.data)
        }
      } catch (e) {
        // 如果不是JSON格式，直接显示
        appendMessage("收到消息: " + event.data)
      }
    }
    
    // 连接关闭的回调方法
    websocket.onclose = () => {
      appendMessage("WebSocket连接已关闭")
    }
  } else {
    alert('当前浏览器不支持WebSocket')
  }
}

// 发送消息
const onSubmit = () => {
  if (!websocket || websocket.readyState !== WebSocket.OPEN) {
    alert('WebSocket连接未建立')
    return
  }
  
  if (!form.value.id || !form.value.dataValue) {
    alert('请填写接收用户ID和消息内容')
    return
  }
  
  // 解析用户ID
  const userIds = form.value.id.split(',').map(id => id.trim()).filter(id => id);

  // 构造要发送的消息对象并分别发送
  userIds.forEach(userId => {
    const message = {
      fromUserId: myId,
      toUserId: userId,
      message: form.value.dataValue
    }
    
    // 发送消息
    websocket.send(JSON.stringify(message))
    appendMessage(`我发送给用户 ${userId}: ${form.value.dataValue}`)
  })
  
  // 清空输入框
  form.value.dataValue = ''
  form.value.id = ''
}

// 关闭WebSocket连接
const closeWebSocket = () => {
  if (websocket) {
    websocket.close()
  }
}

// 将消息追加到消息显示区域
const appendMessage = (message) => {
  formdata.value.dataValue += message + '\n'
  
  // 自动滚动到底部
  setTimeout(() => {
    const textarea = document.querySelector('.el-textarea__inner')
    if (textarea) {
      textarea.scrollTop = textarea.scrollHeight
    }
  }, 0)
}

// 组件挂载时初始化WebSocket
onMounted(() => {
  initWebSocket()
})

// 组件卸载时关闭WebSocket连接
onUnmounted(() => {
  closeWebSocket()
})
</script>

<template>
  
  <br/>
  <el-form :inline="true" :model="form" label-width="auto" style="max-width: 600px">
    <div >我的ID：{{myId}}</div>
    <el-form-item label="接收消息的用户">
      <el-input v-model="form.id" placeholder="请输入用户ID，多个ID用逗号分隔" />
    </el-form-item>
     <el-form-item label="消息">
      <el-input v-model="form.dataValue" placeholder="请输入要发送的消息" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">发送</el-button>
   
    </el-form-item>
    <br/>
    </el-form>
    <el-form :model="formdata" label-width="auto" style="max-width: 600px; min-height: 900px;">
    <el-form-item label="收到的消息：">
      <el-input
        v-model="formdata.dataValue"
        type="textarea"
        :rows="15"
        placeholder="在这里查看收到的消息"
        style="width: 100%;"
        readonly
      />
    </el-form-item>
    </el-form>

</template>

<style scoped>
</style>